package com.ktjy.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ktjy.dto.RoleDTO;
import com.ktjy.pojo.SysRole;
import com.ktjy.service.ISysRoleService;
import com.ktjy.utils.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 角色信息表 前端控制器
 * </p>
 *
 * @author jjx
 * @since 2025-07-31
 */
@RestController
@RequestMapping("/api/sys/role")
public class SysRoleController {
    Logger log= LoggerFactory.getLogger(SysRoleController.class);

    @Autowired
    ISysRoleService sysRoleService;
    
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        List<SysRole> list = sysRoleService.list();
        return AjaxResult.success(list);
    }
    
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPerm('system:role:list')")
    public AjaxResult list(RoleDTO roleDTO,
                           @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                           @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize){
        IPage<SysRole> page = sysRoleService.findPage(roleDTO, pageNo, pageSize);
        return AjaxResult.success(page);
    }

    @PostMapping("/save")
    public AjaxResult saveOrUpdate(@RequestBody SysRole sysRole){
        try {
            sysRoleService.saveOrUpdateRole(sysRole);
            return AjaxResult.success("保存成功");
        } catch (Exception e) {
            log.error("SysRoleController中saveOrUpdate方法执行报错的。",e);
        }
        return AjaxResult.error("保存失败");
    }

    @GetMapping("/view/{id}")
    public AjaxResult view(@PathVariable("id") Long id){
        //查询用户详情
        try {
            SysRole sysRole=sysRoleService.findRole(id);
            return AjaxResult.success(sysRole);
        } catch (Exception e) {
            log.error("SysRoleController中view方法执行报错的。",e);
        }
        return AjaxResult.error();
    }

    @DeleteMapping("/del/{id}")
    public AjaxResult del(@PathVariable("id") Long id){
        try {
            sysRoleService.deleteRole(id);
            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            log.error("SysRoleController中del方法执行报错的。",e);
        }
        return AjaxResult.error("删除失败");
    }

    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysRole sysRole) {
        try {
            sysRoleService.assignDataScope(sysRole);
            return AjaxResult.success("分配数据权限成功");
        } catch (Exception e) {
            log.error("SysRoleController中dataScope方法执行报错的。",e);
        }
        return AjaxResult.error("分配数据权限失败");
    }
}
